﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FileDeleteNew
{
    public partial class UserControlLog : UserControl
    {
        string delPath = "";
        string jsonPath = Application.StartupPath + "\\LogConfig.json";
        private List<FileClass> items = new List<FileClass>();//存储JSON数据数
        Timer delTimer, cbTimer;
        public UserControlLog()
        {
            InitializeComponent();
            LoadData();
            InitializeFileMonitor();
        }

        private void InitializeFileMonitor()
        {
            // 
            delTimer = new Timer(); // 设置定时器间隔为60秒（1分钟）
            delTimer.Interval = 30000;
            delTimer.Tick += new EventHandler(DelTimer_Tick);

            cbTimer = new Timer();
            cbTimer.Interval = 1000;
            cbTimer.Tick += new EventHandler(CBTimer_Tick);
        }
        private void DelTimer_Tick(object sender, EventArgs e)
        {
            if (cb_State.Checked)
            {

                int deleteDay = Convert.ToInt32(txt_DelTime.Text);
                // 使用线程安全的方式调用后台线程
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() => DeleteFile(deleteDay)));
                }
                else
                {
                    DeleteFile(deleteDay);
                }
            }
        }
        public void StartDelTimer()
        {
            delTimer.Start();
        }
        private void CBTimer_Tick(object sender, EventArgs e)
        {
            if (txt_FileLocation.Text == "" || txt_DelTime.Text == "")
            {
                cb_State.Enabled = false;
            }
            else
            {
                cb_State.Enabled = true;
            }
        }
        public void StartCBTimer()
        {
            cbTimer.Start();
        }
        private void LoadData()
        {
            if (File.Exists(jsonPath))
            {
                string json = File.ReadAllText(jsonPath);
                items = JsonConvert.DeserializeObject<List<FileClass>>(json);
            }
            else
            {
                File.Create(jsonPath);
                File.WriteAllText(jsonPath,"[]");
            }
        }
        private void btn_OpenFile_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            folderBrowser.Description = "请选择文件夹";
            folderBrowser.SelectedPath = string.Empty;
            DialogResult dr = folderBrowser.ShowDialog();
            if (dr == DialogResult.OK)
            {
                delPath = folderBrowser.SelectedPath;
                txt_FileLocation.Text = delPath;
            }
            else
            { }
        }
        private void DeleteFile(int saveDay)
        {
            try
            {
                //string fileOriginAll = txt_FileLocation.Text + "\\Origin\\ALL\\";
                string fileOrigin = txt_FileLocation.Text + "\\Origin\\";

                //string fileRenderAll = txt_FileLocation.Text + "\\Render\\ALL\\";
                string fileRender = txt_FileLocation.Text + "\\Render\\";

                DateTime nowTime = DateTime.Now;
                string[] filesorigin = Directory.GetDirectories(fileOrigin, "*.*", SearchOption.AllDirectories);  //获取该目录下所有文件    
                string[] filesrender = Directory.GetDirectories(fileRender, "*.*", SearchOption.AllDirectories);  //获取该目录下所有文件    
                foreach (string file in filesorigin)
                {
                    FileInfo fileInfo = new FileInfo(file);
                    string[] fileSplit = file.Split('\\');
                    string fileTime = fileSplit[fileSplit.Length - 1];
                    if (fileTime == "ALL")
                    {
                        continue;
                    }
                    DateTime dateTime = DateTime.Parse(fileTime.Trim());
                    TimeSpan tDay = nowTime - dateTime;
                    int tDayTime = tDay.Days;
                    //TimeSpan t = nowTime - fileInfo.CreationTime;  //当前时间  减去 文件创建时间               
                    //int day = t.Days;
                    if (tDayTime > saveDay)   //保存的时间 ；  单位：天                
                    {
                        Directory.Delete(file, true);  //删除超过时间的文件夹               
                    }
                }
                foreach (string file in filesrender)
                {
                    FileInfo fileInfo = new FileInfo(file);
                    string[] fileSplit = file.Split('\\');
                    string fileTime = fileSplit[fileSplit.Length - 1];
                    if (fileTime == "ALL")
                    {
                        continue;
                    }
                    DateTime dateTime = DateTime.Parse(fileTime.Trim());
                    TimeSpan tDay = nowTime - dateTime;
                    int tDayTime = tDay.Days;
                    //TimeSpan t = nowTime - fileInfo.CreationTime;  //当前时间  减去 文件创建时间               
                    //int day = t.Days;
                    if (tDayTime > saveDay)   //保存的时间 ；  单位：天                
                    {
                        Directory.Delete(file, true);  //删除超过时间的文件夹               
                    }
                }

            }
            catch (Exception e)
            {
                MessageBox.Show("请选择流程文件路径，请勿选择其他非流程文件！\\" + e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally { }
        }

    }
}
